import {CMD_TYPE, PackageFactory} from "./tp/BluWifiConfigTp";
import EventUtils from "../utils/EventUtils";
import {BuffUtils} from "../utils/BuffUtils";
import MessageConfig from "../config/MessageConfig";
import BluDeviceComService from "./BluDeviceComService";
import {showInfo} from "@/utils/ToastUtils";
// import moment from "moment";
import {
    saveDevice,
    getDeviceInfo,
    getMqttParam,
} from "@/api/device/index";
import {
    getClientDeviceInfo
} from "@/api/gateway/index";

class BluWifiConfigService {

    constructor() {
        console.log("构造 constructor BluWifiConfigService")
        this.configIndex = -1;
        EventUtils.on(MessageConfig.WIFI_CONFIG_RESPONSE, this.handleConfigData);
        setInterval(async () => {
            if (this.configIndex > -1) {
                if (!!this.nowTime && Date.now() - this.nowTime > 12000) {
                    this.configIndex = -1;
                    !!this.callback.error && this.callback.error();
                }
            }
            if (this.configIndex == 8) {
                if (this.count <= 10) {
                    this.count++;
					const clientInfoResult = await getClientDeviceInfo([this.productKey + "." + this.deviceName]);
					console.log("clientInfoResult", clientInfoResult);
					const clientInfo = clientInfoResult.obj;
					console.log("clientInfo", clientInfo);
					if (clientInfo.length > 0) {
					    console.log("客户端已存在设备", clientInfo, this.count);
					    console.log("发送配置信息 configIndex ====================================================", this.configIndex);
					    this.sendConfig();
					    return;
					} else {
					    console.log("设备未在线", clientInfo, this.count);
					}
                } else {
                    !!this.callback.error && this.callback.error();
                }
            }
        }, 2000)
    }

    closeEvent() {
        console.log("设备数据监听销毁");
        EventUtils.off(MessageConfig.WIFI_CONFIG_RESPONSE, this.handleConfigData);
    }

    handleConfigData = async (devicePackage) => {
        this.nowTime = Date.now();
        console.log("WIFI_CONFIG_RESPONSE", devicePackage);
        console.log("this", this);
        const {body} = devicePackage;
        console.log("收到设备信息 body", body.type);
        switch (body.type) {
            case CMD_TYPE.GetBluMac:
                // showInfo("收到设备mac地址：" + body.mac);
                console.log("mac地址", body.mac);
                try {
                    let deviceName = body.mac;
                    console.log("设备保存====================================================");
					const deviceInfo = await getDeviceInfo({
					    deviceName,
					    productKey: this.productKey
					});
					if(!deviceInfo.obj) {
					    console.log("设备不存在，需要注册");
					    const result = await saveDevice({
					        deviceName,
					        productKey: this.productKey,
					    })
					} else {
					    console.log("设备已存在");
					}
                    this.deviceName = deviceName;
                    console.log("询问设备信息=================================================");
                    const infoResult = await getDeviceInfo({
                        productKey: this.productKey,
                        deviceName: deviceName,
                    });
					this.info = infoResult.obj;
                    let mqttParamResult = await getMqttParam({productKey: this.productKey, deviceName});
					console.log("mqttParamResult=========================================", mqttParamResult);
					let mqttParam = mqttParamResult.obj;
					console.log("mqttParam=========================================", mqttParam);

                    const {clientId, username, passwd, mqttHostUrl, port} = mqttParam;
                    this.configData = {
                        wifi: this.wifi,
                        wifiPass: this.wifiPass,
                        deviceName,
                        deviceId: this.deviceId,
                        clientId,
                        username,
                        passwd,
                        mqttHostUrl: "mqtt://" + mqttHostUrl,
                        port
                    };
                    this.configIndex = 0;
                } catch (e) {
                    //重置
                    this.configIndex = -1;
                    console.log("获取信息err", e);
                    // showInfo(JSON.stringify(e));
                    console.log("this.callback", this.callback);
                    !!this.callback && !!this.callback.error && this.callback.error();
                    return;
                }
                break;
            case CMD_TYPE.WriteWifiName:
                if (this.configIndex == 1)
                    return;
                this.configIndex = 1;
                break;
            case CMD_TYPE.WriteWifiPassword:
                if (this.configIndex == 2)
                    return;
                this.configIndex = 2;
                break;
            case CMD_TYPE.WriteMqttUrl:
                if (this.configIndex == 3)
                    return;
                this.configIndex = 3;
                break;
            case CMD_TYPE.WriteMqttPort:
                if (this.configIndex == 4)
                    return;
                this.configIndex = 4;
                break;
            case CMD_TYPE.WriteMqttId:
                if (this.configIndex == 5)
                    return;
                this.configIndex = 5;
                break;
            case CMD_TYPE.WriteMqttUsername:
                if (this.configIndex == 6)
                    return;
                this.configIndex = 6;
                break;
            case CMD_TYPE.WriteMqttPassword:
                if (this.configIndex == 7)
                    return;
                this.configIndex = 7;
                break;
            case CMD_TYPE.NetworkConfigured:
                if (this.configIndex == -1)
                    return;
                this.configIndex = -1;
                // 发送配网成功的消息
                !!this.callback && !!this.callback.finish && this.callback.finish(this.info);
                return;
            case CMD_TYPE.WifiConnected:
                if (this.configIndex == 8)
                    return;
                this.configIndex = 8; //步骤到请求中
                this.count = 0;
                return;
            // 等待设备联网成功
            case CMD_TYPE.ConnectWifi:
                console.log("收到正在连接wifi");
                return;
        }
        console.log("发送配置信息 configIndex ====================================================", this.configIndex);
        this.sendConfig();
    }

    /**
     * 开始配置
     * @param productKey  产品的key
     * @param deviceId    连接后蓝牙设备id
     * @param wifi        用户输入的wifi
     * @param wifiPass    用户输入的wifipass
     * @param callback
     * @returns {Promise<void>}
     */
    config = async ({productKey, deviceId, wifi, wifiPass}, callback) => {
        console.log("productKey", productKey);
        console.log("deviceId", deviceId);
        console.log("wifi", wifi);
        console.log("wifiPass", wifiPass);

        this.callback = callback;
        this.productKey = productKey;
        this.deviceId = deviceId;
        this.wifi = wifi;
        this.wifiPass = wifiPass;
        this.configIndex = -1;
        this.nowTime = Date.now();

        this.configData = {
            wifi: this.wifi,
            wifiPass: this.wifiPass,
            deviceName: "",
            deviceId: this.deviceId,
            clientId: "",
            username: "",
            passwd: "",
            mqttHostUrl: "",
            port: "",
        }

        if (!!this.httpTimeFlag) {
            clearInterval(this.httpTimeFlag);
            this.httpTimeFlag = undefined;
        }
        // 发送开始的消息
        this.sendConfig();
    }

    sendConfig = () => {
        console.log("sendConfig", this.configData);

        const {wifi, wifiPass, deviceName, deviceId, clientId, username, passwd, mqttHostUrl, port} = this.configData;
        let packageArr;
        switch (this.configIndex) {
            // 询问设备mac
            case -1:
                packageArr = PackageFactory.getPackageArr(CMD_TYPE.GetBluMac, []);
                console.log("发送询问mac");
                !!this.callback && !!this.callback.start && this.callback.start();
                break;
            // 发送wifi
            case 0:
                packageArr = PackageFactory.getPackageArr(CMD_TYPE.WriteWifiName, wifi);
                console.log("发送wifi", wifi);
                break;
            // 发送wifi密码
            case 1:
                packageArr = PackageFactory.getPackageArr(CMD_TYPE.WriteWifiPassword, wifiPass);
                console.log("发送wifi密码", wifiPass);
                break;
            // 发送url
            case 2:
                packageArr = PackageFactory.getPackageArr(CMD_TYPE.WriteMqttUrl, mqttHostUrl);
                console.log("发送url", mqttHostUrl);
                break;
            // 发送端口
            case 3:
                let bytes = BuffUtils.intToBigBytes(port, 2);
                packageArr = PackageFactory.getPackageArr(CMD_TYPE.WriteMqttPort, bytes);
                console.log("发送端口", port);
                break;
            // 发送clientid
            case 4:
                packageArr = PackageFactory.getPackageArr(CMD_TYPE.WriteMqttId, clientId);
                console.log("发送clientid", clientId);
                break;
            // 发送用户名
            case 5:
                packageArr = PackageFactory.getPackageArr(CMD_TYPE.WriteMqttUsername, username);
                console.log("发送用户名", username);
                break;
            // 发送密码
            case 6:
                packageArr = PackageFactory.getPackageArr(CMD_TYPE.WriteMqttPassword, passwd);
                console.log("发送密码", passwd);
                break;
            // 发送配网完成
            case 7:
                packageArr = PackageFactory.getPackageArr(CMD_TYPE.ConnectWifi, undefined);
                console.log("等待连接wifi");
                break;
            // 发送配网完成
            case 8:
                packageArr = PackageFactory.getPackageArr(CMD_TYPE.NetworkConfigured, undefined);
                console.log("发送配网");
                break;
        }
        !!this.callback.step && this.callback.step(this.configIndex);
        if (!!packageArr)
            this.sendData(deviceId, packageArr);
    }

    async sendData(deviceId, arr) {
        try {
            let success = await BluDeviceComService.sendData(deviceId, arr)
            console.log("写入是否成成功", success);
            if (!success) {
                console.log("写入失败");
                !!this.callback.error && this.callback.error();
            }
        } catch (err) {
            console.log("写入失败");
            console.log("sendData", err);
        }
    }

}

export default BluWifiConfigService;
